/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers.admin.gift;

import app.Const;
import app.models.DaoKit;
import app.models.gift.Gift;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.datatables.core.DatatablesCriterias;
import com.github.sog.libs.AppFunc;
import com.github.sog.plugin.sqlinxml.SqlKit;
import com.google.common.base.Strings;
import org.apache.commons.lang3.BooleanUtils;

import java.util.List;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-05-28 12:21
 * @since JDK 1.6
 */
public class GiftController extends BasicController {

    public static final String FORM_ATTR = "gift";

    /**
     * The index route.
     */
    public void index() {
        render("index.ftl");
    }


    public void list() {
        final DatatablesCriterias criterias = getCriterias();
        String filter_name = getPara("_name");
        String filter_code = getPara("_code");
        renderDataTables(Gift.dao.datatable(criterias, filter_code, filter_name), criterias);
    }

    public void create() {
        Gift gift = new Gift();
        setAttr(FORM_ATTR, gift);
        setAttr(Const.ACTION_ATTR, Const.CREATE_ACTION);
        render("item.ftl");
    }

    public void edit() {

        Gift gift = Gift.dao.findById(getPara());
        setAttr(FORM_ATTR, gift);
        String pictures = gift.getStr("picture");
        if(!Strings.isNullOrEmpty(pictures)){
            final List<String> pics = AppFunc.COMMA_SPLITTER.splitToList(pictures);
            setAttr("pics", pics);
        }
        setAttr(Const.ACTION_ATTR, Const.EDIT_ACTION);
        render("item.ftl");
    }

    public void remove() {
        String remove_ids = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(remove_ids);
        if (DaoKit.batch_remove(SqlKit.sql("gift.remove"), ids)) {
            renderSuccess();
        } else {
            renderError("删除出现错误");
        }
    }

    public void save() {
        Gift gift = getModel(Gift.class);
        gift.set("hot", BooleanUtils.toBooleanObject(getPara("hot", "off")));

        if (DaoKit.isNew(gift)) {
            gift.save();
        } else {
            gift.update();
        }
        redirect("/admin/gift/gift");
    }

    public void stop(){
        String ids_param = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(ids_param);
        if(Gift.dao.batch_stop(ids)){
            renderSuccess();
        } else {
            renderError("停用礼品信息出错");
        }
    }
    public void start(){
        String ids_param = getPara(Const.DATA_PARAM);
        List<String> ids = AppFunc.COMMA_SPLITTER.splitToList(ids_param);
        if(Gift.dao.batch_start(ids)){
            renderSuccess();
        } else {
            renderError("启用礼品信息出错");
        }
    }
}